package com.gs.synedocket.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Paint;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.gs.synedocket.R;
import com.gs.synedocket.activity.base.BaseActivity;
import com.gs.synedocket.apiresult.ApiResultData;
import com.gs.synedocket.apiresult.LoginData;
import com.gs.synedocket.constant.AllConstants;
import com.gs.synedocket.constant.EventCode;
import com.gs.synedocket.constant.HandleCode;
import com.gs.synedocket.db.bean.Event;
import com.gs.synedocket.db.dao.LogUtil;
import com.gs.synedocket.db.dto.UserDto;
import com.gs.synedocket.dialog.LoadingDialogUtils;
import com.gs.synedocket.dialog.ToastDialogUtils;
import com.gs.synedocket.presenter.LoginPresenter;
import com.gs.synedocket.util.AppUtil;
import com.gs.synedocket.util.CountDownTimerUtil;
import com.gs.synedocket.util.GsonUtil;
import com.gs.synedocket.util.LanguageUtils;
import com.gs.synedocket.util.PermissionUtil;
import com.gs.synedocket.util.RSAUtil;
import com.gs.synedocket.util.SPUtil;
import com.gs.synedocket.util.ToastUtil;
import com.gs.synedocket.view.ILoginView;

import org.greenrobot.eventbus.EventBus;

import java.util.Locale;

public class LoginActivity extends BaseActivity<ILoginView, LoginPresenter> implements ILoginView {

    private EditText etUserName, etPassword;
    private Button btnLogin;
    private TextView tvReset;
    private String publicKey;
    private CountDownTimerUtil util;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        PermissionUtil.addPermission(this, new String[]{
                Manifest.permission.REQUEST_INSTALL_PACKAGES,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.FOREGROUND_SERVICE,
                Manifest.permission.CAMERA,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.CHANGE_NETWORK_STATE}, 1);
        PermissionUtil.addIgnoringBatteryOptimizations(this);
        etUserName = fd(R.id.et_user_name);
        String userName = SPUtil.getInstance().getString(AllConstants.USER);
        etUserName.setText(userName);
        etUserName.setSelection(userName.length());
        etPassword = fd(R.id.et_password);
        btnLogin = fd(R.id.btn_login);
        tvReset = fd(R.id.tv_reset);
        TextPaint paint = tvReset.getPaint();
        paint.setFlags(Paint.UNDERLINE_TEXT_FLAG);
        paint.setAntiAlias(true);
        RadioGroup rg = fd(R.id.rg_language);
        rg.check(SPUtil.getInstance().getInt(AllConstants.LANGUAGE, 1) == 1 ? R.id.rb_chinese : R.id.rb_english);
        rg.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
        TextView tvVersion = fd(R.id.tv_version);
        tvVersion.setText(String.format("V%s", AppUtil.getInstance().getVersion()));
        MyOnClickListener onClickListener = new MyOnClickListener();
        tvReset.setOnClickListener(onClickListener);
        btnLogin.setOnClickListener(onClickListener);
    }

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    @Override
    public String getUserName() {
        return etUserName.getText().toString();
    }

    @Override
    public String getPassword() {
        return etPassword.getText().toString();
    }

    @Override
    public String getEncryptPassword() {
        if (TextUtils.isEmpty(publicKey)) {
            return null;
        }
        return RSAUtil.encrypt(getPassword(), publicKey);
    }

    @Override
    public String getImei() {
        return AppUtil.getInstance().getIMEI();
    }

    @Override
    public void onLoginSuccess(ApiResultData<LoginData> apiResultData) {
        btnLogin.setEnabled(true);
        if (apiResultData.getStatus() != 2000) {
            ToastDialogUtils.getInstance().showInfoMessage(this, apiResultData.getMessage());
            return;
        }
        UserDto userInfo = apiResultData.getData().getUserInfo();
        String loginInfo = GsonUtil.getInstance().toJson(userInfo);
        SPUtil.getInstance().putString(AllConstants.USER, userInfo.getUserName());
        SPUtil.getInstance().putString(AllConstants.LOGIN_INFO, loginInfo);
        SPUtil.getInstance().putString(AllConstants.ID, userInfo.getId());
        SPUtil.getInstance().putString(AllConstants.TRUCK_NAME, userInfo.getTruckNo() == null ? "" : userInfo.getTruckNo());
        SPUtil.getInstance().putString(AllConstants.TOKEN,
                apiResultData.getData().getToken() == null ? "" : apiResultData.getData().getToken());
        SPUtil.getInstance().putString(AllConstants.REFRESH_TOKEN,
                apiResultData.getData().getRefreshToken() == null ? "" : apiResultData.getData().getRefreshToken());
        LogUtil.getInstance().insertOrReplaceData(apiResultData.getMessage());
        jump();
    }

    @Override
    public void onLoginFail(Exception e) {
        btnLogin.setEnabled(true);
        ToastDialogUtils.getInstance().showInfoMessage(this, R.string.network_error);
    }

    @Override
    public void onGetKeySuccess(ApiResultData<String> apiResultData) {
        if (apiResultData.getStatus() != 2000) {
            btnLogin.setEnabled(true);
            ToastDialogUtils.getInstance().showInfoMessage(this, apiResultData.getMessage());
            return;
        }
        publicKey = apiResultData.getData();
        mPresenter.login();
    }

    @Override
    public void onGetKeyFail(Exception e) {
        btnLogin.setEnabled(true);
        ToastDialogUtils.getInstance().showInfoMessage(this, R.string.network_error);
    }

    @Override
    public void onResetSuccess(ApiResultData<String> apiResultData) {
        ToastDialogUtils.getInstance().showInfoMessage(this, apiResultData.getMessage());
        if (apiResultData.getStatus() != 1000) {
            return;
        }
        startCountDown();
    }

    private void startCountDown() {
        if (util == null) {
            util = new CountDownTimerUtil(60 * 1000, new CountDownTimerUtil.OnResponseListener() {
                @Override
                public void onTick(long millisUntilFinished) {
                    tvReset.setText(getString(R.string.reset2, millisUntilFinished / 1000));
                    tvReset.setClickable(false);
                    tvReset.setEnabled(false);
                    tvReset.setTextColor(getResources().getColor(R.color.color_8c));
                }

                @Override
                public void onFinish() {
                    tvReset.setText(getString(R.string.reset));
                    tvReset.setClickable(true);
                    tvReset.setEnabled(true);
                    tvReset.setTextColor(getResources().getColor(R.color.login_tv_color));
                }
            });
        } else {
            util.startCountDown();
        }
    }

    @Override
    public void onResetFail(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(this, R.string.network_error);
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(this);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

    class MyOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.rb_chinese) {
                changeLanguage(1, Locale.TAIWAN);
            } else if (checkedId == R.id.rb_english) {
                changeLanguage(2, Locale.ENGLISH);
            }
        }
    }

    private void changeLanguage(int languageId, Locale locale) {
        SPUtil.getInstance().putInt(AllConstants.LANGUAGE, languageId);
        LanguageUtils.getInstance().change(locale);
        EventBus.getDefault().post(new Event(EventCode.EVENT_LANGUAGE));
    }

    class MyOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_login:
                    if (TextUtils.isEmpty(getUserName())) {
                        ToastUtil.showToast(R.string.p_input_username);
                        return;
                    }
                    if (TextUtils.isEmpty(getPassword())) {
                        ToastUtil.showToast(R.string.p_input_pw);
                        return;
                    }
                    if (TextUtils.isEmpty(getImei())) {
                        ToastUtil.showToast(R.string.p_agree_permission);
                        PermissionUtil.addPermission(LoginActivity.this, new String[]{
                                Manifest.permission.READ_PHONE_STATE,Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                        return;
                    }
                    v.setEnabled(false);
                    mPresenter.getKey();
                    break;
                case R.id.tv_reset:
                    if (TextUtils.isEmpty(getUserName())) {
                        ToastUtil.showToast(R.string.p_input_username);
                        return;
                    }
                    mPresenter.reset(getUserName());
                    break;
            }
        }
    }

    private void jump() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(AllConstants.WHAT, HandleCode.MSG_LOGIN);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (util != null) {
            util.cancelCountDown();
        }
    }
}